package org.haredot.service.impl;

import org.haredot.entity.Position;
import org.haredot.mapper.PositionMapper;
import org.haredot.service.PositionService;
import org.haredot.vo.ResultVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

@Service
@Transactional(rollbackFor = Exception.class)
public class PositionServiceImpl implements PositionService {

    @Resource
    private PositionMapper positionMapper ;

    @Override
    public ResultVo<?> queryPositions() {

        List<Position> list = positionMapper.findAllPositions();
        return ResultVo.ok().data(list).build();
    }

    @Override
    public ResultVo<?> savePosition(Position position) {
        Position pos = positionMapper.findByName(position.getName());

        if (pos !=null) {
            return ResultVo.fail("岗位名称已存在").build();
        }

        int len = positionMapper.insert(position);

        return ResultVo.ok().build();
    }

    @Override
    public ResultVo<?> modifyPosition(Long id, Position position) {

        Position pos = positionMapper.findByName(position.getName());

        if (pos!=null && !Objects.equals(pos.getId(), id)) {
            return ResultVo.fail("岗位名称已存在").build();
        }
        position.setId(id);
        int len = positionMapper.updateByPrimaryKey(position);

        return ResultVo.asserts(len == 1, "数据修改失败").build();
    }

    @Override
    public ResultVo<?> removePosition(Long id) {
        int len = positionMapper.deleteByPrimaryKey(id);
        return ResultVo.asserts(len == 1, "数据删除失败").build();
    }
}
